#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define EMMC_CAPACITY 64 // eMMC容量，单位GB

int readFromFile(const char *path, char *emmcsize_char, size_t size)
{
    FILE *fp = fopen(path, "r");
    if (!fp) {
        printf("Failed to open file: %s\n", path);
        return -1;
    }

    size_t count = fread(emmcsize_char, 1, size, fp);
    fclose(fp);

    if (count > 0) {
        while (count > 0 && emmcsize_char[count - 1] == '\n') {
            count--;
        }
        emmcsize_char[count] = '\0';
    } else {
        emmcsize_char[0] = '\0';
    }

    return count;
}

int get_emmc_size(char *size_data)
{
    int count;
    int emmc_size=1;
    double size = (double)(atoi(size_data))/2/1024/1024;

    if (size > 0 && size <= 1)  /*1 GB */
        return 1;
    for (count = 1; count < 10; count++)
    {
        if ((size > emmc_size) && (size <= emmc_size*2))   /*2 - 512 GB*/
            return emmc_size*2;

        emmc_size *=2;
    }
    return -1;
}

int emmc_test()
{
    int emmc_ret = 0;
    char emmcsize_char[20];
    int emmc_size = 0;
    const char *emmc_path = "/sys/bus/mmc/devices/mmc1:0001/block/mmcblk1/size";

    printf("=======  eMMC test starting   ========\n");

    memset(emmcsize_char, 0, sizeof(emmcsize_char));
    if (readFromFile(emmc_path, emmcsize_char, sizeof(emmcsize_char)) >= 0) {
        emmc_size = get_emmc_size(emmcsize_char);
        if (emmc_size < 0) {
            emmc_ret = -1;
            goto fail;
        }
        printf("eMMC size: %s GB\n", emmcsize_char);
        printf("eMMC capacity: %d GB\n", emmc_size);
        if (EMMC_CAPACITY != emmc_size) {
            goto fail;
        }
    } else {
        goto fail;
    }

    printf("eMMC test successful\n");
    return 0;

fail:
    printf("eMMC test failed\n");
    return -1;
}

int main()
{
    if (emmc_test() == 0) {
        printf("emmc 测试成功\n");
        system("echo \"$(date)：emmc 测试成功\" >> /userfs/all.txt");
    } else {
        printf("emmc 测试失败\n");
        system("echo \"$(date)：emmc 测试失败\" >> /userfs/all.txt");
    }

    return 0;
}
